import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import User from '../components/user/User'

Vue.use(Router)

//原理是啥？？没这个配置，点二级菜单报错，虽然页面可以正常跳转，项目可以正常运行
//原因是elementUI 的导航栏router重复点击会报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/', redirect: '/login'
    },
    {
      path: '/login', component: Login
    },
    {
      path: '/home', component: Home,
      redirect: '/welcome',
      children: [
        {
          path: '/welcome', component: Welcome
        }, {
          path: '/userList', component: User
        }
      ]
    }
  ]
})

// 挂载，路由导航守卫
router.beforeEach((to, from, next) => {

  //to将要访问的路径，from代表从哪个路径跳转来的，next是一个函数，表示放行
  if (to.path === '/login') {
    return next()
  }
  const token = window.sessionStorage.getItem('token');
  //token为空时转到登陆页，至于token是否相等，在后端判断
  if (token === null) {
    return next('/login')
  }
  next()
})


export default router
